package Client;

import common.Message.RpcRequest;
import common.Message.RpcResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IOClient：建立连接、发送请求、接收响应、异常处理
 */
public class IOClient {

    private static final Logger logger = LoggerFactory.getLogger(IOClient.class);

    /**
     * 请求远程服务
     *
     * @param host    主机名
     * @param port    端口名
     * @param request RpcRequest请求对象
     * @return null
     */
    public static RpcResponse sendRequest(String host, int port, RpcRequest request) {

        try {
            // 创建Socket对象
            Socket socket = new Socket(host, port);
            // 将对象序列化发送到服务端
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            // 接受并反序列化对象
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            // 将RpcRequest对象序列化兵发送到服务端
            objectOutputStream.writeObject(request);
            objectOutputStream.flush();

            // 接受并反序列化RpcResponse对象
            RpcResponse response = (RpcResponse) objectInputStream.readObject();
            return response;

            // 与网络通信相关的异常、反序列化对象时找不到对应类的异常
        } catch (IOException e) {
            logger.info("IOClient.sendRequest error:", e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return null;
    }
}
